<?php

namespace Admin\Controller;

use Think\Controller;

class TglinkController extends CommonController
{
    public function add()
    {

        $spmodel = D('Shipin');
        if (IS_POST) {
            $cfmodel = D('Config');
            $cfdata = $cfmodel->field('zym,dwz')->find();
            $data = $_POST['data'];
            $tgmode = M('Tglink');
            $t = $spmodel->field('id,name,zykey,url')->where(['id' => ['in', $data]])->select();
            $arr = [];
            $arr1 = [];
            foreach ($t as $v) {
                $biaoshi = substr(md5($v['zykey']), 0, 10);//标识无意义
                $url =$cfdata['zym'] . 'index.php/home/login/login?code=' . $v['zykey'] . $biaoshi;
                $longurl = urlencode($url);
                $arr['userid'] = session('uid');
                $arr['name'] = $v['name'];
                $arr['code'] = $v['zykey'] . $biaoshi;
                $arr['shortlink'] = dwzlink($longurl, $cfdata['dwz']);//
                if (!$tgmode->where(array('shortlink' => $arr['shortlink']))->find()) {
                    $tgmode->add($arr);
                }
                array_push($arr1, $arr);
            }
            $arr1 = json_encode($arr1);
            echo $arr1;
        } else {
            $spdata = $spmodel->field('id,name,zykey,url')->where(['userid' => ['eq', 'admin']])->select();
            // 设置页面中的信息
            $this->assign(array(
                'spdata' => $spdata,
            ));
            $this->display();

        }


    }

    public function edit()
    {
        $id = I('get.id');
        if (IS_POST) {
            $model = D('Tglink');
            if ($model->create(I('post.'), 2)) {
                if ($model->save() !== FALSE) {
                    $this->success('修改成功！', U('lst', array('p' => I('get.p', 1))));
                    exit;
                }
            }
            $this->error($model->getError());
        }
        $model = M('Tglink');
        $data = $model->find($id);
        $this->assign('data', $data);

        // 设置页面中的信息
        $this->assign(array(
            '_page_title' => '修改',
            '_page_btn_name' => '列表',
            '_page_btn_link' => U('lst'),
        ));
        $this->display();
    }

    public function delete()
    {
        $model = D('Tglink');
        if ($model->delete(I('get.id', 0)) !== FALSE) {
            $this->success('删除成功！', U('lst', array('p' => I('get.p', 1))));
            exit;
        } else {
            $this->error($model->getError());
        }
    }

    public function lst()
    {
        $model = D('Tglink');
        $data = $model->search();
        $this->assign(array(
            'data' => $data['data'],
            'page' => $data['page'],
        ));

        // 设置页面中的信息
        $this->assign(array(
            '_page_title' => '列表',
            '_page_btn_name' => '添加',
            '_page_btn_link' => U('add'),
        ));
        $this->display();
    }
}